# -*- coding: utf-8 -*-
# @Time     : 2021/11/30 15:17
# @Author   : wljess
# @File     : buyTicket.py
# @Describe : 
# @Software : PyCharm

import time
import json
from multiprocessing import Process, Lock


def search_ticket(num):
    with open('ticket', 'r') as f:
       data = json.loads(f.read())
       print(f"用户{num}查看剩余票数：{data['count']}")


def buy_ticket(user):
    time.sleep(0.02)

    with open('ticket', 'r') as rf:
        data = json.loads(rf.read())
        if data['count'] > 0:
            print(f"{user}买到票了...")
            data['count'] -= 1
        else:
            print(f"尚无余票,用户{user}没有买到票")

    time.sleep(0.02)
    with open("ticket", "w") as wf:
        wf.write(json.dumps(data))


def task(num, lock_):
    search_ticket(num)
    with lock_:
        buy_ticket(num)


if __name__ == '__main__':

    lock = Lock()

    for i in range(10):
        p = Process(target=task, args=(i, lock))
        p.start()

